E) C/C++ Thread Programming

Multi Thread Programming with C/C++
아래 방법은 직접 연산을 각 스레드에 할당해 주어야 하는 Static Thread Programming
C
pthread: POSIX thread
#include <pthread.h>
#include <stdio.h>
#include <limits.h>
pthread_mutex_t mutex_lock=PTHREAD_MUTEX_INITIALIZER;
long long int g_count; // Thread Communication Global Variable
void* threadF(void* data){
char* thread_name=(char*)data;
pthread_mutex_lock(&mutex_lock);
printf("%s start: g_count=%lld\n", thread_name, g_count);
for(int i=INT_MIN; i<INT_MAX; ++i) g_count++;
printf("%s end: g_count=%lld\n", thread_name, g_count);
pthread_mutex_unlock(&mutex_lock);
}
int main(void){
pthread_t pthread[3];
int status;
pthread_create(&pthread[0], NULL, threadF, (void*)"Thread1");
pthread_create(&pthread[1], NULL, threadF, (void*)"Thread2");
pthread_create(&pthread[2], NULL, threadF, (void*)"Thread3");
pthread_join(pthread[0], (void*)&status);
pthread_join(pthread[1], (void*)&status);
pthread_join(pthread[2], (void*)&status);
return 0;
}
C++
thread
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
std::mutex mtx;
//std::recursive_mutex mtx;
void Sum(int start, int finish, int* result){
int sum=0;
for(int i=start+1; i<finish+1; ++i){
sum+=i;
}
*result=sum;
std::thread::id this_id=std::this_thread::get_id();
mtx.lock();
std::cout<<'['<<this_id<<']'<<"From "<<start+1<<" To "<<finish<<" Result: "<<sum<<std::endl;
mtx.unlock();
}
int main(void){
const int number=100000;
const int threadN=10;
std::vector<int> partialSum(threadN);
std::vector<std::thread> threads;
for(int i=0; i<threadN; ++i){
threads.push_back(
std::thread(Sum, number/threadN*i, number/threadN*(i+1), &partialSum[i])
);
}
for(int i=0; i<threadN; ++i) threads[i].join();
long long int sum=0;
for(int i=0; i<threadN; ++i) sum+=partialSum[i];
std::cout<<"Total Sum: "<<sum<<std::endl;
return 0;
}
std::mutex        ; lock(), unlock() 메소드
위에서 lock이 되어있는 쓰레드에 대해 lock이 또 호출될 경우, 미정의 동작이 발생(unlock도 동일)
try_lock()을 통해 권환을 확인 하거나, std::recursive_lock을 이용
std::lock_guard<std::recursive_mutex> lg(mtx);
lock_guard는 RAII(Resource Acquistion Is Initialization) 방식을 따른다.
즉, 범위를 벗어나면 자동적으로 lock을 해제한다.
mutex의 메소드 호출이 가능한 std::unique_lock
std::timed_mutex, std::recursive_timed_mutex 등을 제공

try_lock_until(), try_lock_for()...